package handler

import (
	"context"
	"fmt"
	"math/rand"
	"server/basic/global"
	"server/basic/inits"
	"server/models"
	__ "server/proto"
	"time"
	"unicode"
)

type Server struct {
	__.UnimplementedUserServer
}

func IsNum(s string) bool {
	for _, v := range s {
		if !unicode.IsDigit(v) {
			return false
		}
	}
	return true
}
func (s *Server) Sendsms(_ context.Context, in *__.SendsmsRequest) (*__.SendsmsResponse, error) {
	if len(in.Mobile) != 11 || !IsNum(in.Mobile) {
		return nil, fmt.Errorf("请填写正确的电话号码")
	}
	code := rand.Intn(9000) + 1000
	inits.RedisClient.Set(context.Background(), "sendsms"+in.Mobile+in.Score, code, time.Minute*5)
	key := "sms_number" + in.Mobile
	result, err := inits.RedisClient.Exists(context.Background(), key).Result()
	if err != nil {
		return nil, fmt.Errorf("系统错误")
	}
	if result == 1 {
		return nil, fmt.Errorf("一分钟只能发送一次 稍后再试")
	}
	err = inits.RedisClient.Set(context.Background(), key, "1", time.Second*60).Err()
	if err != nil {
		return nil, fmt.Errorf("系统错误")
	}
	return &__.SendsmsResponse{}, nil
}

// SayHello implements helloworld.GreeterServer
func (s *Server) Login(_ context.Context, in *__.LoginRequest) (*__.LoginResponse, error) {
	if len(in.Mobile) != 11 || !IsNum(in.Mobile) {
		return nil, fmt.Errorf("请填写正确的电话号码")
	}
	number := "sms_number" + in.Mobile
	result, err2 := inits.RedisClient.Exists(context.Background(), number).Result()
	if err2 != nil {
		return nil, fmt.Errorf("系统错误")
	}
	if result == 0 {
		return nil, fmt.Errorf("验证码已过期")
	}
	key := "sendsms" + in.Mobile + "login"
	get := inits.RedisClient.Get(context.Background(), key)
	if get.Val() != in.Sendsms {
		return nil, fmt.Errorf("短信验证码错误")
	}
	err := inits.RedisClient.Del(context.Background(), key).Err()
	if err != nil {
		return nil, fmt.Errorf("验证码删除失败")
	}

	add := models.VideoUser{
		Mobile: in.Mobile,
	}
	return &__.LoginResponse{
		Id: int64(add.Id),
	}, nil
}
func (s *Server) ListWork(_ context.Context, in *__.ListWorkRequest) (*__.ListWorkResponse, error) {
	var find []models.VideoUser
	global.DB.Find(&find)
	var finds []*__.List
	for _, v := range find {
		lists := &__.List{
			Name:          v.Name,
			NickName:      v.NickName,
			UserCode:      v.UserCode,
			Signature:     v.Signature,
			Sex:           v.Sex,
			IpAddress:     v.IpAddress,
			Constellation: v.Constellation,
			AttendCount:   v.AttendCount,
			FansCount:     v.FansCount,
			ZanCount:      v.ZanCount,
			Status:        v.Status,
			Age:           int64(v.Age),
			AvatorFileId:  int64(v.AvatorFileId),
		}
		finds = append(finds, lists)
	}
	return &__.ListWorkResponse{
		List: finds,
	}, nil
}
func (s *Server) AddWork(_ context.Context, in *__.AddWorkRequest) (*__.AddWorkResponse, error) {
	var find models.VideoMusic
	err := global.DB.Where("id = ?", in.Id).Find(&find).Error
	if err != nil {
		return nil, fmt.Errorf("查询失败")
	}
	add := models.VideoWorks{
		Title:          in.Title,
		Desc:           in.Desc,
		MusicId:        int32(in.MusicId),
		WorkType:       in.WorkType,
		CheckStatus:    in.CheckStatus,
		IpAddress:      in.IpAddress,
		WorkPermission: in.WorkPermission,
		LikeCount:      int32(in.LikeCount),
		CommentCount:   int32(in.CommentCount),
		ShareCount:     int32(in.ShareCount),
		CollectCount:   int32(in.CollectCount),
		BrowseCount:    int32(in.BrowseCount),
		TopicId:        int32(in.TopicId),
		UserId:         int32(in.UserId),
	}
	err = global.DB.Create(&add).Error
	if err != nil {
		return nil, fmt.Errorf("作品添加失败")
	}
	return &__.AddWorkResponse{
		Id: int64(add.Id),
	}, nil
}
func (s *Server) Comment(_ context.Context, in *__.CommentRequest) (*__.CommentResponse, error) {
	var find models.VideoWorkComment
	err := global.DB.Where("pid =?", in.Pid).Find(&find).Error
	if err != nil {
		return nil, fmt.Errorf("父级评论不存在 无法进行评论")
	}
	add := models.VideoWorkComment{
		WorkId:  int32(in.WorkId),
		UserId:  int32(in.UserId),
		Content: in.Content,
		Tag:     int32(in.Tag),
		Pid:     int32(in.Pid),
	}
	err = global.DB.Create(&add).Error
	if err != nil {
		return nil, fmt.Errorf("添加评论失败")
	}
	return &__.CommentResponse{
		CreatedAt: time.DateTime,
	}, nil
}
